<template>
  <div class="ant-result-icon">
    <a-button type="primary" @click="addService" v-has="{ a: $route, b: 2 }" class="d-a-center">新增</a-button>
    <!-- 左侧一级分类服务列表 这个要手写？这样位置有点奇怪啊感觉着可以再写一个table表格啊哈-->
    <div class="header fl">
      <div class="tab" :class="{ active: active == index }" v-for="(item, index) in tabs" :key="index" @click="handleChange1(index)">
        {{ item.kindName }}
      </div>
    </div>
    <div class="main">
      <a-table :columns="serviceColums" :data-source="serviceList" style="width: 200px" :pagination="false">
        <template #service="{ record, index }">
          <div class="service" @click="getChildrenList(record.id, index)">
            <div class="name" :class="index == serviceAct ? 'name-act' : ''">
              {{ record.name }}
            </div>
            <!-- <div  v-has="{a:$route,b:2}" class="edit" @click="editService(record, 1)">
              <EditTwoTone />
            </div>
             -->
          </div>
        </template>
      </a-table>
      <!--右侧二级分类列表 -->
      <div style="flex: 1">
        <a-table
          :columns="childrenColums"
          :data-source="childrenList"
          bordered
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <!-- :scroll="{ y: 540, x: 'auto' }" -->

          <template #service="{ record, index }">
            <div class="service">
              <div class="name" :class="index == serviceAct ? 'name-act' : ''" @click="getChildrenList(record.id, index)">
                {{ record.name }}
              </div>
              <div class="edit" danger v-has="{ a: $route, b: 2 }" @click="editService(record, 1)">
                <EditTwoTone />
              </div>
              <div class="del" danger v-has="{ a: $route, b: 2 }" @click="delService(record.key)">
                <DeleteTwoTone twoToneColor="#f5222d" />
              </div>
            </div>
          </template>
          <!-- <template #sort="{ record, index }" v-has="{ a: $route, b: 2 }">
						<div v-has="{ a: $route, b: 2 }" style="display: flex; justify-content: space-between">
							<div @click="up(record.id, index)">
								<ArrowUpOutlined style="color: red" />
							</div>
							<div @click="down(record.id, index)">
								<ArrowDownOutlined />
							</div>
						</div>
					</template> -->
          <template #isConsumable="{ record, index }">
            <div v-has="{ a: $route, b: 2 }" @click="checkConsumable(record.isConsumable, index, record.id)">
              <a-switch v-model:checked="record.isConsumable" :checkedValue="1" :unCheckedValue="0" />
            </div>
          </template>
          <template #isDown="{ record, index }">
            <div v-has="{ a: $route, b: 2 }" @click="changeStack(record.isDown, index, record.id)">
              <a-switch v-model:checked="record.isDown" :checkedValue="0" :unCheckedValue="1" />
            </div>
          </template>
          <template #operation="{ record }">
            <a-button type="link" @click="editService(record, 0)" v-has="{ a: $route, b: 2 }">编辑</a-button>
            <a-button type="link" danger v-has="{ a: $route, b: 2 }" @click="delService(record.key, 0)">删除</a-button>
          </template>
        </a-table>
      </div>
    </div>
  </div>
  <div>
    <!-- 工作流程 -->
    <a-modal :visible="flowPop" :footer="null" width="50%" @cancel="closeFlowPop">
      <div class="flowWrap">
        <a-form ref="formRef" name="dynamic_form_nest_item" :model="dynamicValidateForm" @finish="onFinish">
          <div class="f_item">
            <div class="left"><span class="spot">*</span> 服务规范</div>
            <div class="right">
              <a-form-item
                :name="['serveName']"
                :rules="{
                  required: true,
                  message: '请输入服务规范'
                }"
              >
                <a-input v-model:value="dynamicValidateForm.serveName" placeholder="请输入服务规范"></a-input>
              </a-form-item>
            </div>
          </div>
          <div class="f_item">
            <div class="left"><span class="spot">*</span> 规范详情</div>
            <div class="right">
              <div class="flex" style="margin-left: -174px; margin-bottom: 10px">
                <div class="tip">示列：</div>
                <div class="flex">
                  <a-form-item>
                    <a-input :disabled="true" value="一、联系客户" />
                  </a-form-item>
                  <a-form-item style="margin-left: 22px">
                    <a-textarea
                      class="myhtml"
                      :disabled="true"
                      :auto-size="{ minRows: 4 }"
                      value="1.确认服务时间，地点\n 2.确认客户耗材准备情况\n 3.确认医嘱信息是否齐全"
                    ></a-textarea>
                  </a-form-item>
                </div>
              </div>
              <a-space v-for="(user, index) in dynamicValidateForm.users" :key="user.id">
                <div style="display: flex; align-items: center; margin-bottom: 8px; margin-left: 80px !important">
                  <!-- <div class="tip" style="opacity: 0; margin-left: 30px">
                    示列：
                  </div> -->
                  <a-form-item
                    :name="['users', index, 'first']"
                    :rules="{
                      required: true,
                      message: '请输入标题'
                    }"
                  >
                    <a-input v-model:value="user.first" placeholder="请输入标题" />
                  </a-form-item>
                  <a-form-item
                    style="margin-left: 16px"
                    :name="['users', index, 'last']"
                    :rules="{
                      required: true,
                      message: '请输入具体步骤。'
                    }"
                  >
                    <a-textarea
                      v-model:value="user.last"
                      :auto-size="{ minRows: 5 }"
                      placeholder="请输入具体步骤。如有多个步骤，请换行输入"
                    />
                  </a-form-item>
                  <MinusCircleOutlined @click="removeUser(user)" />
                </div>
              </a-space>
              <a-form-item>
                <a-button type="dashed" block @click="addUser">
                  <PlusOutlined />
                  添加工作流程步骤
                </a-button>
              </a-form-item>
              <a-form-item>
                <a-row style="margin-top: 20px">
                  <a-col :span="4" :offet="8" style="margin-left: 40%">
                    <a-button @click="closeFlowPop">关闭</a-button>
                  </a-col>
                  <a-col span="2" offet="8">
                    <a-button type="primary" html-type="submit">保存</a-button>
                  </a-col>
                </a-row>
              </a-form-item>
            </div>
          </div>
        </a-form>
      </div>
    </a-modal>
    <!-- 服务项目 -->
    <a-modal :visible="visible" :footer="null" width="90%" @cancel="cancel">
      <a-tabs v-model:activeKey="activeKey" class="user">
        <a-tab-pane key="0" :tab="headerTitle + '服务项目'" v-if="type == 0 || type == 2">
          <!-- 新增服务项 -->
          <a-form ref="modalRef" :rules="rules" :model="modalForm" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-item label="服务名称" name="name">
              <a-input placeholder="请输入服务名称" v-model:value="modalForm.name"></a-input>
            </a-form-item>
            <a-form-item label="服务类型" name="valueList">
              <a-cascader
                v-model:value="valueList"
                placeholder="请选择服务类型"
                :options="typeList"
                @change="typeChange"
                :load-data="loadData"
                change-on-select
                :field-names="{
                  label: 'name',
                  value: 'id'
                }"
              />
            </a-form-item>
            <a-form-item label="服务排序" name="sort">
              <a-input placeholder="请输入大于0的服务排序数字" v-model:value="modalForm.sort" type="number"></a-input>
            </a-form-item>
            <a-form-item label="只为权益卡服务" name="isDown">
              <a-select ref="select" v-model:value="modalForm.isDown" @focus="focus" @change="handleMyChange" placeholder="请选择是或否">
                <a-select-option v-for="item in buyCar1" :value="item.id + ''" :key="item.id">{{ item.name }} </a-select-option>
              </a-select>
              <!-- <a-input placeholder="" v-model:value="modalForm.sort"></a-input> -->
            </a-form-item>
            <a-form-item label="价格" name="price">
              <!-- <a-input
                style="width: 100px"
                v-model:value="modalForm.price"
              /> -->
              <a-input-number :min="0.01" max="9999" v-model:value="modalForm.price"></a-input-number>

              <span style="margin-left: 10px">元</span>
            </a-form-item>
            <a-form-item label="市场价格" name="mallPrice">
              <a-input-number :min="0.01" max="9999" v-model:value="modalForm.mallPrice"></a-input-number>

              <span style="margin-left: 10px">元</span>
            </a-form-item>
            <a-form-item label="时长" name="hours">
              <!-- <a-input
                v-model:value="modalForm.hours"
                style="width: 100px"
              /> -->
              <a-input-number :min="1" max="9999" v-model:value="modalForm.hours"></a-input-number>
              <span style="margin-left: 10px">分钟</span>
            </a-form-item>
            <a-form-item label="服务简介" name="introduction">
              <a-textarea placeholder="请输入服务简介" v-model:value="modalForm.introduction"></a-textarea>
            </a-form-item>
            <a-form-item label="佣金结算" name="serviceWindRatio">
              <a-input v-model:value="modalForm.serviceWindRatio" suffix="%"></a-input>
            </a-form-item>
            <a-form-item label="热门服务排序" name="popularSort">
              <a-input placeholder="请输入大于0的热门服务排序数字" v-model:value="modalForm.popularSort" type="number"></a-input>
            </a-form-item>
            <a-form-item label="热门服务封面" name="popularImgUrl">
              <a-upload
                v-model:file-list="popularImgUrlList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="popularImage"
                :before-upload="beforeUpload"
              >
                <div v-if="popularImgUrlList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="服务封面" name="coverJsonImg">
              <a-upload
                v-model:file-list="fileList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage"
                :before-upload="beforeUpload"
              >
                <!--  @change="handleChange1" -->
                <div v-if="fileList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>

            <a-form-item label="服务内容图" name="contentPictureImg">
              <!-- {{ imgList.length ? "已上传" : "未上传" }} -->
              <!-- <div v-if="imgList.length > 0"> -->
              <img style="height: 50px; width: 50px" :src="item.url" v-for="(item, index) in imgList" :key="index" alt="" />
              <!-- </div> -->

              <a-button @click="handleAddContentImgOpen" class="d-a-center"> 编辑服务内容图</a-button>
            </a-form-item>
            <!--  @change="handleChange1" -->
            <a-form-item label="产品介绍" name="productIntroduce">
              <a-upload
                v-model:file-list="fileList2"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage2"
                :before-upload="beforeUpload"
              >
                <div v-if="fileList2.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>

            <!-- 新增 -->
            <a-form-item label="服务概述" name="serviceOverview">
              <a-upload
                v-model:file-list="serviceOverviewList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="serviceUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="serviceOverviewList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="适用人群" name="applicablePeople">
              <a-upload
                v-model:file-list="applicablePeopleList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="peopleUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="applicablePeopleList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="服务流程" name="serviceProcess">
              <a-upload
                v-model:file-list="serviceProcessList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="processUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="serviceProcessList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="服务须知" name="serviceInstructions">
              <a-upload
                v-model:file-list="serviceInstructionsList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="instructionsUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="serviceInstructionsList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="费用须知" name="feeNotice">
              <a-upload
                v-model:file-list="feeNoticeList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="feeUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="feeNoticeList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="护理风险知情同意书" name="userInformedBook">
              <a-upload
                v-model:file-list="fileList5"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage5"
                :before-upload="beforeUpload"
              >
                <div v-if="fileList5.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="免责协议" name="disclaimer">
              <a-upload
                v-model:file-list="fileList3"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadImage4"
                :before-upload="beforeUpload"
              >
                <div v-if="fileList3.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="三级分类图标" name="imgUrl">
              <a-upload
                v-model:file-list="imgUrlList"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="imgUrlUploadImage"
                :before-upload="beforeUpload"
              >
                <div v-if="imgUrlList.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="三级图标跳转链接" name="jumpLink">
              <a-input placeholder="请输入三级图标跳转链接" v-model:value="modalForm.jumpLink"></a-input>
            </a-form-item>
            <a-form-item label="服务告知书" name="serviceNotice">
              <a-textarea v-model:value="modalForm.serviceNotice" :auto-size="{ minRows: 3 }" placeholder="请输入服务告知书" />
            </a-form-item>
            <a-form-item label="服务详情" name="serviceDetails">
              <div class="f_item">
                <a-button type="dashed" block @click="addServiceDetail" class="d-c-center">
                  <PlusOutlined />
                  添加项目
                </a-button>
                <div class="right">
                  <a-space v-for="(service, index) in serviceDetails" :key="index">
                    <div style="display: flex; align-items: center; margin-bottom: 8px; margin-left: 50px !important">
                      <a-input v-model:value="service.serviceDetailTitle" placeholder="请输入标题" />
                      <a-textarea v-model:value="service.serviceDetail" :auto-size="{ minRows: 3 }" placeholder="请输入描述" />
                      <!-- </a-form-item> -->
                      <MinusCircleOutlined @click="removeService(index)" />
                    </div>
                  </a-space>
                </div>
              </div>
            </a-form-item>
            <a-form-item label="工作流程" name="dataFlow">
              <div class="flow">
                <table class="table">
                  <tr>
                    <th class="header" v-for="item in columnsFlow" :key="item.serveName">
                      {{ item.title }}
                    </th>
                  </tr>
                  <tr v-for="(tr, index) in dataFlow" :key="index">
                    <td v-for="(i, ind) in columnsFlow" :key="ind">
                      <div>{{ tr[i.dataIndex] }}</div>
                      <div v-if="i.dataIndex == 'operation'">
                        <a @click="handleEditFlow(tr, index)">编辑</a>
                        <a style="opacity: 0">辑</a>
                        <a-popconfirm v-if="dataSource.length" title="确定删除?" @confirm="handleDeleteDataFlow(index)">
                          <a style="display: inline-block; margin-left: 8rpx">删除</a></a-popconfirm
                        >
                      </div>
                    </td>
                  </tr>
                </table>

                <a-button type="dashed" block @click="handleFlowPop" class="d-c-center">
                  <PlusOutlined />
                  新增服务规范
                </a-button>
              </div>
            </a-form-item>
            <a-form-item label="套餐列表" name="dataSource">
              <a-button class="editable-add-btn d-a-center" style="margin-bottom: 8px; margin-top: 10px" @click="handleAdd"
                >添加套餐</a-button
              >
              <div>
                <table class="table">
                  <tr>
                    <th class="header" v-for="item in columns" :key="item.name">
                      {{ item.title }}
                    </th>
                  </tr>
                  <tr v-for="(tr, index) in dataSource" :key="index">
                    <template v-if="tr.isEdit" class="edit_class">
                      <td v-for="(i, ind) in columns" :key="ind">
                        <div v-if="i.dataIndex == 'operation'">
                          <a-button type="link" v-if="tr.isEdit" @click="handleSave">保存</a-button>

                          <!-- <a-button type="link" @click="handleDelete(index)">编辑</a-button> -->
                        </div>
                        <input v-else type="link" v-model="obj[i.dataIndex]" />
                      </td>
                    </template>
                    <template v-else>
                      <td v-for="(i, ind) in columns" :key="ind">
                        <div>{{ tr[i.dataIndex] }}</div>
                        <div v-if="i.dataIndex == 'operation'">
                          <a-popconfirm v-if="dataSource.length" title="确定删除?" @confirm="handleDelete(index)">
                            <a-button type="link">删除</a-button></a-popconfirm
                          >
                          <a-button type="link" @click="handleEdit(index)">编辑</a-button>
                        </div>
                      </td>
                    </template>
                  </tr>
                </table>
              </div>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <!-- 新增服务类别 -->
        <a-tab-pane key="1" :tab="headerTitle + '服务类别'" force-render v-if="type == 1 || type == 2">
          <a-form ref="modalRef1" :model="modalForm1" :rules="rules1" :wrapper-col="{ span: 8 }" style="margin-top: 20px">
            <a-form-item :label="headerTitle + '服务类别'" name="name">
              <a-input placeholder="请输入服务类别" v-model:value="modalForm1.name"></a-input>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
      <a-divider></a-divider>
      <!-- 确定和取消 -->
      <a-row>
        <a-col :span="4" :offset="8">
          <a-button type="primary" size="large" @click="save">保存</a-button>
        </a-col>
      </a-row>
    </a-modal>
    <a-modal :visible="imgVisible" :footer="null" width="50%" @cancel="handleClose">
      <div class="wrap">
        <a-table :columns="myColums" :data-source="imgList" bordered :loading="loading" :customRow="customRow">
          <template #url="{ record }">
            <img style="width: 60px; height: 60px" :src="record.url" alt="" />
          </template>
          <template #operation="{ record, index }">
            <a-button type="link" @click="delMyImg(index)"> 删除</a-button>
          </template>
        </a-table>
        <a-row>
          <a-col :span="4" :offset="8">
            <a-upload
              v-show="imgList.length < 8"
              v-model:file-list="fileLists"
              list-type="picture-card"
              class="avatar-uploader"
              :maxCount="8"
              :customRequest="uploadImage3"
              :before-upload="beforeUpload"
            >
              <!--  @change="handleChange1" -->
              <div class="ant-upload-text">
                <plus-outlined />
              </div>
            </a-upload>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="2" :offset="9">
            <a-form-item>
              <a-button type="primary" @click="handleAddContentImg">保存</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { reactive, ref, watch, watchEffect, computed, defineComponent, createVNode, toRefs } from 'vue'
import { FormInstance } from 'ant-design-vue'
import applyBG from '@/assets/img/home/apply-bg.png'
import industryBG from '@/assets/img/home/industry-bg.png'
import userBG from '@/assets/img/home/user-bg.png'
import templateBG from '@/assets/img/home/template-bg.png'
import activeBG from '@/assets/img/home/active-bg.png'
import {
  CheckOutlined,
  EditOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  ExclamationCircleOutlined,
  EditTwoTone,
  DeleteTwoTone,
  PlusOutlined,
  MinusCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons-vue'
import { Modal, message, notification } from 'ant-design-vue'
import Tinymce from '@/components/common/tinymce/tinymce'
import Tinymce1 from '@/components/common/tinymce/tinymce1'
import {
  selectAllService,
  updateAndAddService,
  updateOrAddType,
  deleteService,
  selectServiceById,
  uploadPicture,
  serviceUpOrDown,
  updateGoodIsConsumable
} from '@/api/service/index.js'
import * as api from '@/api/service/index.js'
import { throttle } from '@/assets/js/debounceThrottle.js'
import UploadImage from '@/components/common/UploadImage.vue'
import { useModal } from '@/hooks'
export default {
  setup() {
    const serviceAct = ref(0)
    let change1 = null // 源目标数据序号
    let changeObj = null // 源目标数据序号
    let change2 = null
    const data = reactive({
      servic: '',
      // 一级二级联动
      valueList: [],
      valueListl: [],
      serviceList: [],
      childrenList: [],
      loading: true, //表格加载
      // headerTitle: "",
      isEdit: '', //编辑or新增
      type: 2, //类型
      visible: false,
      activeKey: '0',
      uploadLoading: false,
      imageUrl: '',
      modalForm1: {},
      modalForm: {
        detail: ''
      },
      value: '',
      fileList: [],
      fileLists: [],
      fileList2: [],
      fileList3: [],
      fileList5: [],
      threeTypeId: 1,
      imgUrlList: [], //三级分类图标
      feeNoticeList: [], //费用须知
      serviceInstructionsList: [], //服务须知
      serviceProcessList: [], //服务流程
      applicablePeopleList: [], //适用人群
      serviceOverviewList: [], //服务概述
      popularImgUrlList: [],
      detail: '哈哈哈',
      uploadRef: '',
      active: 0,
      imgList: [],
      imgVisible: false,
      columns: [
        {
          title: '套餐名称',
          dataIndex: 'sonServiceName',
          width: '30%'
        },
        {
          title: '套餐价格(元)',
          dataIndex: 'price'
        },
        {
          title: '套餐时长(分钟)',
          dataIndex: 'duration'
        },
        {
          title: '服务次数',
          dataIndex: 'serviceNum'
        },

        {
          title: '市场价格',
          dataIndex: 'mallPrice'
        },
        {
          title: '佣金结算比例',
          dataIndex: 'commissionSettlementRatio'
        },
        {
          title: '佣金结算金额',
          dataIndex: 'commissionSettlementAmount'
        },
        {
          title: '操作',
          dataIndex: 'operation'
        }
      ],
      flowPop: false,
      columnsFlow: [
        {
          title: '服务规范',
          dataIndex: 'serveName',
          width: '70%'
        },
        {
          title: '操作',
          dataIndex: 'operation'
        }
      ],
      // 工作流程数据
      dataFlow: [
        // {
        //  id:0
        //   name: "服务流程",
        //   operation: "",
        // },
      ],
      dataSource: [],
      obj: {},
      // 修改当前套餐的index
      flag: -1,
      serviceDetails: [],
      tabs: [],
      // 二级id
      secondId: 0,
      typeList: [],
      buyCar1: [
        {
          name: '是',
          id: 1
        },
        {
          name: '否',
          id: 0
        }
      ]
    })
    const state = reactive({
      fileList: [],
      mdl: {
        fileList: []
      }
    })
    watchEffect(() => {
      if (state.fileList.length === 0) {
        state.mdl = []
      } else {
        state.mdl.fileList = JSON.stringify(state.fileList)
      }
    })
    watch(
      () => data.imgList,
      () => {
        console.log('asdasdas')
      }
    )
    const modalRef = ref('')
    const modalRef1 = ref('')
    const editor = ref('')
    const editor1 = ref('')

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 5,
      total: 0
    })

    // 左侧服务分类列表
    const serviceColums = [
      {
        title: '服务名称',
        dataIndex: 'name',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'service'
        }
      }
    ]
    const myColums = [
      {
        title: '图片',
        dataIndex: 'url',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'url'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'operation'
        }
      }
    ]
    const childrenColums = [
      {
        title: '服务项目',
        dataIndex: 'serveName',
        className: 'table',
        align: 'center'
      },
      {
        title: '排序',
        dataIndex: 'sort',
        className: 'table',
        align: 'center'
      },
      {
        title: '价格',
        dataIndex: 'servePrice',
        className: 'table',
        align: 'center'
        // sorter: (a, b) => a.price - b.price,
      },
      {
        title: '服务时长',
        dataIndex: 'serveTimeOrNumber',
        className: 'table',
        align: 'center'
      },
      {
        title: '介绍',
        dataIndex: 'introduce',
        className: 'table',
        align: 'center'
        // ellipsis: true,
      },
      {
        title: '耗材记录',
        dataIndex: 'isDown',
        className: 'table',
        slots: {
          customRender: 'isConsumable'
        }
      },
      {
        title: '上下架',
        dataIndex: 'isDown',
        className: 'table',
        slots: {
          customRender: 'isDown'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      // console.log(pagination, "当前分页");
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      initChildrenList()
    }
    // 新增服务
    const addService = () => {
      data.valueList = []
      data.fileList = []
      data.fileList2 = []
      data.fileList3 = []
      data.imgUrlList = [] //三级分类
      data.feeNoticeList = [] //费用须知
      data.serviceInstructionsList = [] //服务须知
      data.serviceProcessList = [] //服务流程
      data.applicablePeopleList = [] //适用人群
      data.serviceOverviewList = [] //服务概述
      data.popularImgUrlList = []
      data.dataSource = []
      data.imgList = []
      data.visible = true
      data.serviceDetails = []
      data.modalForm.typeId = ''
      data.isEdit = 2
      data.type = 2
      data.activeKey = '0'
      data.typeList = data.tabs.map(el => {
        el.name = el.kindName
        return el
      })
      data.flag = -1
      // data.valueList[0]= data.typeList[0].id
      console.log(data.typeList, '----')
    }
    // 编辑服务和服务项目
    const editService = async (item, type) => {
      data.visible = true
      data.type = type
      data.isEdit = 1
      data.activeKey = String(type) //激活类型是
      console.dir(item)
      if (type == 1) {
        data.modalForm1 = {
          name: item.name,
          id: item.id
        }
        data.visible = true
      } else {
        let res = await initServiceDetail(item.id)
        console.log('详情', res)
        data.servic = res.typeId
        console.log(data.servic)
        if (res.isDown == 0) {
          res.isDown = '否'
        } else {
          res.isDown = '是'
        }
        res.typeId = String(res.typeId) //服务ID是string类型的
        data.modalForm = res

        data.imgList = res.contentPicture
          ? res.contentPicture.split(',').map(m => {
              return {
                url: m
              }
            })
          : []

        data.valueList = [res.parentId, res.typeId]

        data.modalForm.typeId = data.valueList[1]
        console.log(data.valueList[1])

        data.valueList = res.serviceKindName

        data.serviceDetails = [...(res.serviceDetails || [])]
        data.fileList = res.coverJson ? [{ url: res.coverJson }] : []
        data.fileList2 = res.productIntroduce ? [{ url: res.productIntroduce }] : []
        data.fileList3 = res.disclaimer ? [{ url: res.disclaimer }] : []
        data.fileList5 = res.userInformedBook ? [{ url: res.userInformedBook }] : []
        //三级分类
        data.imgUrlList = res.imgUrl ? [{ url: res.imgUrl }] : []
        //费用须知
        data.feeNoticeList = res.feeNotice ? [{ url: res.feeNotice }] : []
        //服务须知
        data.serviceInstructionsList = res.serviceInstructions ? [{ url: res.serviceInstructions }] : []
        //服务流程
        data.serviceProcessList = res.serviceProcess ? [{ url: res.serviceProcess }] : []
        //适用人群
        data.applicablePeopleList = res.applicablePeople ? [{ url: res.applicablePeople }] : []
        //服务概述
        data.serviceOverviewList = res.serviceOverview ? [{ url: res.serviceOverview }] : []
        data.popularImgUrlList = res.popularImgUrl ? [{ url: res.popularImgUrl }] : []
        if (res.workFlow) {
          data.dataFlow = [...JSON.parse(res.workFlow || '')]
        }
        // data.dataSource = [...res.sonServicesList];
        console.log(data.dataSource, '1002')
        console.log(res.sonServicesList, '1003')
        // let priceList = res.sonServicesList.map((el) => (el.key = el.price));
        let priceList = res.sonServicesList.sort(function (a, b) {
          return a.price - b.price
        })
        data.dataSource = priceList
        // data.value = data.serviceList.find(
        //   (el) => el.id == String(res.typeId)
        // ).name;
        // console.log(data.value, "服务类型是");
        // 放在最后，要不然富文本无法渲染
        //res.sonServicesList里的price按照
        data.visible = true
      }
    }
    async function initServiceDetail(id) {
      let res = await selectServiceById(id)
      // data.dataSource = [...res.sonServicesList];
      if (res.success) {
        return res.object
      }
      console.log(res.object)
    }
    const handleMyChange = v => {
      // console.log(v, "vv");
      data.modalForm.isDown = v == 1 ? '1' : '0'
      console.log(data.modalForm.isDown, 'data.modalForm.isDown')
    }
    // 删除服务和服务项目
    const delService = (key, type) => {
      const { closeModal } = useModal.confirm({
        title: () => '确定删除该服务类型吗?',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () =>
          createVNode(
            'div',
            {
              style: 'color:red;'
            },
            '确定要删除当前服务类型吗'
          ),
        okType: 'danger',
        onOk: async () => {
          let res = await deleteService([Number(key)])
          if (res.success) {
            message.success('删除成功')
            initChildrenList()
            closeModal()
          }
        },

        class: 'test'
      })
    }

    // 获取服务下的子列表:本来写的一级和二级联动，嗯……然后呢？不动了……我……无语了……
    const getChildrenList = (e, index) => {
      if (serviceAct.value == index) return
      serviceAct.value = index
      data.secondId = e
      page.current = 1
      initChildrenList()
    }
    const up = (e, index) => {
      console.log(e, index, '升序')
      const { closeModal } = useModal.confirm({
        title: () => '确定升序吗?',
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let data = await initServiceDetail(e)
          data.sort = 1
          console.log('升序1111111111111', data)
          let res = await updateAndAddService(data)
          if (res.success) {
            initChildrenList()
            message.success('升序成功~')
            closeModal()
          }
        },

        class: 'test'
      })
    }
    const down = (e, index) => {
      console.log(e, index, '降序')
      const { closeModal } = useModal.confirm({
        title: () => '确定降序吗?',
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let data = await initServiceDetail(e)
          data.sort = 1
          console.log('降序2222222222222', data)
          let res = await updateAndAddService(data)
          if (res.success) {
            initChildrenList()
            message.success('排序成功~')
            closeModal()
          }
        },

        class: 'test'
      })
    }
    const checkConsumable = (checked, index, id) => {
      console.log(page.pageNum)
      let title = checked == 0 ? '关闭' : '开启'
      // 弹框提示？确定上下架吗
      const { closeModal } = useModal.confirm({
        title: () => `确认${title}此服务耗材记录吗？?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await updateGoodIsConsumable({
            serviceId: id,
            isConsumable: checked
          })
          if (res.success) {
            initChildrenList()
          } else {
            let flag = checked == 0 ? 1 : 0
            data.childrenList[index].isConsumable = flag
          }
          closeModal()
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0
          data.childrenList[index].isConsumable = flag
          closeModal()
        },
        class: 'test'
      })
    }
    const changeStack = (checked, index, id) => {
      console.log(page.pageNum)
      console.log(checked, index, '是否上下架')
      let title = checked == 0 ? '上架' : '下架'
      // 弹框提示？确定上下架吗
      const { closeModal } = useModal.confirm({
        title: () => `确认${title}此服务项目吗？?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await serviceUpOrDown({
            id,
            isDown: checked
          })
          if (res.success) {
            initChildrenList()
          } else {
            let flag = checked == 0 ? 1 : 0
            data.childrenList[index].isDown = flag
          }
          closeModal()
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0
          data.childrenList[index].isDown = flag
          closeModal()
        },
        class: 'test'
      })
    }
    const headerTitle = computed(() => {
      let title = data.isEdit == 1 ? '编辑' : '新增'
      return title
    })

    const validReason = () => {
      if (!data.dataFlow.length) return Promise.reject('请添加工作流程')
      return Promise.resolve()
    }

    const validValueList = () => {
      if (!data.valueList?.length) return Promise.reject('请输入服务类型')
      return Promise.resolve()
    }

    // const validServiceDetails = () => {
    //   if (!data.serviceDetails.length) return Promise.reject("请添服务详情");
    //   if (
    //     data.serviceDetails[0].serviceDetail == "" ||
    //     data.serviceDetails[0].serviceDetailTitle == ""
    //   )
    //     return Promise.reject("请添服务详情");
    //   return Promise.resolve();
    // };

    const validDataSource = () => {
      if (!data.dataSource.length) return Promise.reject('请添套餐列表')
      if (
        data.dataSource[0].duration == '' ||
        data.dataSource[0].mallPrice == '' ||
        data.dataSource[0].price == '' ||
        data.dataSource[0].serviceNum == '' ||
        data.dataSource[0].sonServiceName == ''
      )
        return Promise.reject('请添套餐列表')
      return Promise.resolve()
    }

    const validCoverJson = () => {
      if (!data.fileList.length) return Promise.reject('请选择服务封面')
      return Promise.resolve()
    }
    const validContentPictureImg = () => {
      if (!data.imgList.length) return Promise.reject('请选择服务内容图')
      return Promise.resolve()
    }
    //服务封面
    // const validImage = () => {
    //   if (!data.fileList.length) return Promise.reject("请添加服务封面");
    //   if (
    //     data.fileList[0].contentJson == ""
    //   )
    //     return Promise.reject("请添加服务封面");
    //   return Promise.resolve();
    // };

    const rules = {
      name: [
        {
          required: true,
          message: '请输入内容标题!',
          trigger: 'change'
        },
        {
          min: 0,
          max: 20,
          message: '文字超出限制范围!',
          trigger: 'blur'
        }
      ],
      sort: [
        {
          required: true,
          message: '请输入大于0的服务排序数字!'
        }
      ],
      // popularSort: [
      //   {
      //     required: true,
      //     message: "请输入大于0的热门服务排序数字!",
      //   },
      // ],
      isDown: [
        {
          required: true,
          message: '请选择是否只为权益卡服务'
        }
      ],
      typeId: [
        {
          required: true,
          message: '请选择服务类型'
        }
      ],
      introduction: [
        {
          required: true,
          message: '请输入服务简介',
          trigger: 'blur'
        }
      ],
      notice: [
        {
          required: true,
          message: '请输入预约须知',
          trigger: 'blur'
        }
      ],
      detail: [
        {
          required: true,
          message: '请输入服务详情',
          trigger: 'blur'
        }
      ],
      price: [
        {
          required: true,
          message: '请输入服务价格'
        }
      ],
      mallPrice: [
        {
          required: true,
          message: '请输入市场价格'
        }
      ],
      serviceNotice: [
        {
          required: true,
          message: '请输入服务告知书'
        }
      ],
      hours: [
        {
          required: true,
          message: '请输入服务时长'
        }
      ],
      serviceWindRatio: [
        {
          required: true,
          message: '请输入结算比例'
        },
        {
          pattern: /^(\d|[1-9]\d|100)(\.\d{1,2})?$/,
          message: '请输入1-100的数，最多保留两位小数'
        }
      ],
      // img: [
      //   {
      //     required: true,
      //     message: "请编辑图片",
      //   },
      // ],
      valueList: [
        {
          required: true,
          validator: validValueList
        }
      ],
      dataFlow: [
        {
          required: true,
          validator: validReason
        }
      ],
      // serviceDetails: [
      //   {
      //     required: true,
      //     validator: validServiceDetails,
      //   },
      // ],
      dataSource: [
        {
          required: true,
          validator: validDataSource
        }
      ],
      coverJsonImg: [
        {
          required: true,
          validator: validCoverJson
        }
      ],
      contentPictureImg: [
        {
          required: true,
          validator: validContentPictureImg
        }
      ]
    }
    const rules1 = {
      name: [
        {
          required: true,
          message: '请输入服务类别!',
          trigger: 'blur'
        }
      ]
    }

    const cancel = () => {
      console.log('点击了关闭')
      let ref = data.activeKey == '0' ? modalRef : modalRef1
      //置空
      data.modalForm1 = {}
      data.modalForm = {}
      data.valueList = []
      data.dataSource = []
      data.dataFlow = []
      ref.value.clearValidate()
      data.flag = -1
      data.visible = false
    }
    const uploadImage2 = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      /*
				   直接打印formData是空的，别人说要通过get才能访问到
				    console.log(formData.get("file"), "上传图片");

				   formData上传的时候不能使用{}包括比如  let data={file:formData,name:'test'}
				    这样上传就是空对象……
				    let res = await uploadPicture(data);

				   只能单独放，这样才可以、和后端说下改下……
				   let res = await uploadPicture(formData);

				*/

      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        // console.log(data.fileList, "fileList列表是");
        data.fileList2 = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
        // data.fileList.shift(1);
      }
      // console.log(data.fileList, "fileList列表是");
    }
    const uploadImage5 = async file => {
      let formData = new FormData()
      formData.append('file', file.file)

      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        data.fileList5 = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    const uploadImage4 = async file => {
      let formData = new FormData()
      formData.append('file', file.file)

      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        data.fileList3 = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    const delMyImg = index => {
      data.imgList.splice(index, 1)
    }
    const uploadImage3 = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        data.imgList.push({
          id: file.file.uid,
          url: res.object
        })
        modalRef.value.validate(['contentPictureImg'])

        data.fileLists = []

        // .push(
        //   {
        //     uid: file.file.uid,
        //     url: res.object,
        //     status: "done",
        //     name: file.file.name,
        //   },
        // );
      }
    }
    const uploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      /*
				   直接打印formData是空的，别人说要通过get才能访问到
				    console.log(formData.get("file"), "上传图片");

				   formData上传的时候不能使用{}包括比如  let data={file:formData,name:'test'}
				    这样上传就是空对象……
				    let res = await uploadPicture(data);

				   只能单独放，这样才可以、和后端说下改下……
				   let res = await uploadPicture(formData);

				*/

      let res = await uploadPicture(formData, 'service')
      // // url存入列表中,为什么是两个fileList
      if (res.success) {
        data.fileList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    const popularImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.popularImgUrlList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //服务概述
    const serviceUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.serviceOverviewList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //适用人群
    const peopleUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.applicablePeopleList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //服务流程
    const processUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.serviceProcessList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //服务须知
    const instructionsUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.serviceInstructionsList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //三级分类
    const imgUrlUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.imgUrlList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }
    //费用须知
    const feeUploadImage = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'service')
      if (res.success) {
        data.feeNoticeList = [
          {
            uid: file.file.uid,
            url: res.object,
            status: 'done',
            name: file.file.name
          }
        ]
      }
    }

    const handleChange = value => {
      data.modalForm.typeId = value
      console.log(data.modalForm.typeId)
    }
    const previewVisible = ref(false)
    const previewImage = ref('')
    const imageUrl = ref('')

    function getBase64(img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    }
    const handleCancel = () => {
      previewVisible.value = false
    }

    const handlePreview = async file => {
      // console.log(file, "上传图片这是");
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }
    // 顶部轮播图
    const handleAddContentImgOpen = () => {
      data.imgVisible = true
    }
    const handleClose = () => {
      data.imgVisible = false
    }

    const handleAddContentImg = () => {
      if (data.imgList.length == 0) {
        message.error('请上传1-8张内容图')
        return
      }

      let arr = data.imgList.map(m => {
        return m.url
      })
      data.modalForm.contentPicture = arr.join(',')
      data.imgVisible = false
    }
    const customRow = (record, index) => {
      //  console.log(record, index);// 这里输出是表格全部的数据
      return {
        props: {
          // draggable: 'true'
        },
        style: {
          cursor: 'pointer'
        },
        // 鼠标移入
        onMouseenter: event => {
          // 兼容IE
          var ev = event || window.event
          ev.target.draggable = true // 让你要拖动的行可以拖动，默认不可以
        },
        // 开始拖拽
        onDragstart: event => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到源目标数据序号
          change1 = index
          changeObj = record
          console.log(record, index, 'source')
        },
        // 拖动元素经过的元素
        onDragover: event => {
          // 兼容 IE
          var ev = event || window.event
          // 阻止默认行为
          ev.preventDefault()
        },
        // 鼠标松开
        onDrop: event => {
          // 兼容IE
          var ev = event || window.event
          // 阻止冒泡
          ev.stopPropagation()
          // 得到目标数据序号
          change2 = index
          // 这里就是让数据位置互换，让视图更新 你们可以看record，index的输出，看是什么
          ;[data.imgList[change1], data.imgList[change2]] = [data.imgList[change2], data.imgList[change1]]
          // if (change1 != change2) {
          //   api
          //     .serviceTypeSort({
          //       downOrUp: change1 > change2 ? 0 : 1,
          //       id: changeObj.id,
          //       targetId: record.id,
          //     })
          //     .then((r) => {
          //       if (r.success) {
          //         initChildrenList();
          //       }
          //     });
          // }

          console.log(record, index, 'target')
        }
      }
    }
    const handleChange1 = index => {
      data.active = index
      initFirstService()
      page.current = 1
      page.total = 0
      data.serviceList = []
      data.childrenList = []
    }

    const beforeUpload = file => {
      const isJpgOrPng =
        file.type === 'image/psd' ||
        file.type === 'image/bmp' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpeg'

      if (!isJpgOrPng) {
        message.error('图片格式不正确!')
      }
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isLt2M) {
        message.error('图片大小不超过5MB!')
      }
      return isJpgOrPng && isLt2M
    }

    // 富文本内容
    const tinymceInput = value => {
      console.log(value, '服务简介')
      data.modalForm.detail = value
    }
    const tinymceInput1 = value => {
      // console.log(value, "预约须知");
      data.modalForm.notice = value
    }
    //服务类型
    const typeChange = (value, selectedOptions) => {
      console.log('value, selectedOptions', value, selectedOptions)
      data.valueListl = value
      console.log('选择1111111111', data.valueListl)
    }
    // 保存,根据tab的绑定的key值判断编辑服务项目还是类别
    const save = throttle(() => {
      let reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
      if (reg.test(data.valueList[1])) {
        // data.valueListl为空导致typeId undefined
        console.log('sisi', data.valueListl)
        if (data.valueListl[1]) {
          data.modalForm.typeId = data.valueListl[1]
        }
      } else {
        data.modalForm.typeId = data.valueList[1]
      }
      console.log('data.modalForm.typeId', data.modalForm.typeId)
      // data.modalForm.typeId = data.valueListl;
      let ref = data.activeKey == '0' ? modalRef : modalRef1
      ref.value
        .validate()
        .then(async () => {
          if (data.activeKey == '0') {
            if (data.modalForm.typeId == '') {
              message.error('请选择服务类型')
            }
            if (data.modalForm.sort < 0) {
              message.error('请输入大于0的服务排序数字')
            }
            if (data.modalForm.popularSort) {
              if (data.modalForm.popularSort <= 0) {
                message.error('请输入大于0的热门服务排序数字')
                return
              }
            }

            if (data.fileList.length == 0) {
              message.error('请上传服务封面')
              return
            }
            if (data.imgList.length == 0) {
              message.error('请上传1-8张服务内容图')
              return
            }
            //服务类型
            // data.modalForm.typeId = data.servic;

            data.modalForm.coverJson = data.fileList[0].url
            console.log(data.modalForm.typeId)
            if (data.fileList2.length > 0) {
              data.modalForm.productIntroduce = data.fileList2[0].url
            } else {
              data.modalForm.productIntroduce = ''
            }
            if (data.popularImgUrlList.length > 0) {
              data.modalForm.popularImgUrl = data.popularImgUrlList[0].url
            } else {
              data.modalForm.popularImgUrl = ''
            }
            //服务概述，适用人群，服务流程，服务须知，费用须知
            if (data.serviceOverviewList.length > 0) {
              data.modalForm.serviceOverview = data.serviceOverviewList[0].url
            } else {
              data.modalForm.serviceOverview = ''
            }
            if (data.applicablePeopleList.length > 0) {
              data.modalForm.applicablePeople = data.applicablePeopleList[0].url
            } else {
              data.modalForm.applicablePeople = ''
            }
            if (data.serviceProcessList.length > 0) {
              data.modalForm.serviceProcess = data.serviceProcessList[0].url
            } else {
              data.modalForm.serviceProcess = ''
            }
            if (data.serviceInstructionsList.length > 0) {
              data.modalForm.serviceInstructions = data.serviceInstructionsList[0].url
            } else {
              data.modalForm.serviceInstructions = ''
            }
            if (data.feeNoticeList.length > 0) {
              data.modalForm.feeNotice = data.feeNoticeList[0].url
            } else {
              data.modalForm.feeNotice = ''
            }
            if (data.imgUrlList.length > 0) {
              data.modalForm.imgUrl = data.imgUrlList[0].url
              data.modalForm.threeTypeId = 1
            } else {
              data.modalForm.imgUrl = ''
              delete data.modalForm.threeTypeId
            }

            data.modalForm.userInformedBook = data.fileList5.length > 0 ? data.fileList5[0].url : ''
            if (data.fileList3.length > 0) {
              data.modalForm.disclaimer = data.fileList3[0].url
            } else {
              data.modalForm.disclaimer = ''
            }
            data.modalForm.contentJson = data.fileList[0].url
          }
          let f1 = false

          // 服务详情
          data.serviceDetails.map(s => {
            if (!s.serviceDetail || !s.serviceDetailTitle) {
              f1 = true
              return
            }
          })
          if (f1) {
            message.error('服务详情请输入完整！')
            return
          }
          data.modalForm.serviceDetails = [...data.serviceDetails]

          // 工作流程和
          // data.modalForm.workFlow = [...data.dataFlow];
          data.modalForm.workFlow = JSON.stringify(data.dataFlow)
          // 套餐列表
          let flag = false
          data.dataSource.map(m => {
            if (!m.sonServiceName || !m.price || !m.duration || !m.serviceNum || !m.mallPrice) {
              flag = true
            }
          })
          if (flag) {
            message.error('请保存套餐列表')
            return
          }
          if (data.isEdit == 1) {
            data.dataSource = data.dataSource.map(d => {
              d.serviceId = data.modalForm.id
              return d
            })
            // data.modalForm.sonServicesList = [...data.dataSource];
            data.modalForm.sonServicesList = data.dataSource
            console.log(data.modalForm.sonServicesList)
          } else {
            // data.modalForm.sonServicesList = [...data.dataSource];
            data.modalForm.sonServicesList = data.dataSource
            console.log(data.modalForm.sonServicesList)
          }
          console.log(data.modalForm.typeId)
          if (data.activeKey == '0') {
            if (data.isEdit == 1) {
              // 编辑服务类别
              if (data.modalForm.isDown == '否' || data.modalForm.isDown == 0) {
                data.modalForm.isDown = 0
              } else if (data.modalForm.isDown == '是' || data.modalForm.isDown == 1) {
                data.modalForm.isDown = 1
              }
              console.log('编辑服务typeId0000000000', data.modalForm)
              // data.modalForm.typeId = data.servic;

              data.modalForm.sonServicesList = [...data.dataSource]
              let res = await updateAndAddService(data.modalForm)
              console.log(data.modalForm, 'data.modalForm')
              if (res.success) {
                message.success('执行成功')
                data.visible = false
                data.dataSource = []
                data.dataFlow = []
                data.modalForm = {}
                initChildrenList()
              }
            } else {
              console.log('新增服务typeId0000000000', data.modalForm)
              let res = await updateAndAddService(data.modalForm)
              if (res.success) {
                data.visible = false
                message.success('执行成功')
                data.modalForm = {}
                initChildrenList()
              }
            }
          } else {
            let res = await updateOrAddType(data.modalForm1)
            if (res.success) {
              message.success('执行成功')
              data.visible = false
              data.modalForm1 = {}
              initServiceList()
            }
          }
          // 关闭弹窗
          // emit('closeModal')
        })
        .catch(error => {
          console.log('error', error)
        })
    }, 2000)
    initFirstService()
    // initServiceList();
    async function initFirstService() {
      api.queryserviceTypeParent().then(r => {
        data.tabs = [...r.object]

        r.object.map(m => (m.name = m.kindName))
        r.object.map(el => (el.isLeaf = false))
        data.typeList = [...r.object]
        initServiceList()
      })
    }

    // 初始化服务列表
    async function initServiceList() {
      let obj = {
        parentId: data.tabs[data.active].id
      }
      let res = await api.selectAllType(obj)
      if (res.success) {
        // res.object.records.map((el) => (el.key = el.id));
        data.serviceList = res.object
        serviceAct.value = 0
        data.secondId = res.object[0].id
        initChildrenList()
      }
    }
    // 二级列表
    async function initChildrenList() {
      data.loading = false
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        typeId: data.secondId
      }
      let res = await selectAllService(obj)
      if (res.success) {
        res.object.records.map(el => (el.key = el.id))
        data.childrenList = res.object.records
        console.log(data.childrenList)
        page.total = res.object.total
      }
      data.loading = false
    }
    const closeFlowPop = () => {
      data.flowPop = false
      formRef.value.resetFields()
      dynamicValidateForm.serveName = ''
      dynamicValidateForm.users = []
      dynamicValidateForm.id = []
      dynamicValidateForm.isEdit = false
    }

    const methods = {
      handleFlowPop() {
        data.flowPop = true
      },
      handleAdd() {
        let idEdit = data.dataSource.some(i => i.isEdit)
        if (idEdit) {
          message.error('当前有正在编辑的套餐,请先保存')
          return
        }
        const newData = {
          key: ``,
          sonServiceName: ``,
          price: '',
          duration: '',
          serviceNum: '',
          commissionSettlementAmount: '',
          commissionSettlementRatio: '',
          mallPrice: '',
          operation: '',
          isEdit: true
        }
        data.dataSource.push(newData)
      },
      handleEdit(ind) {
        let idEdit = data.dataSource.some(i => i.isEdit)
        // if (idEdit) return
        if (idEdit) {
          message.error('当前有正在编辑的套餐,请先保存')
          return
        }
        data.flag = ind
        // data.dataSource = data.dataSource.map(i => i.isEdit=false)
        data.dataSource[ind].isEdit = true
        data.obj = {
          ...data.dataSource[ind],
          isEdit: true
        }
      },
      handleDelete(ind) {
        data.dataSource.splice(ind, 1)
      },
      handleDeleteDataFlow(i) {
        data.dataFlow.splice(i, 1)
      },

      handleSave() {
        if (data.obj.commissionSettlementRatio && data.obj.commissionSettlementRatio > 1) {
          message.error('佣金结算比例范围为0-1 ')
          return
        }
        if (data.obj.commissionSettlementAmount && data.obj.commissionSettlementRatio) {
          message.error('佣金结算比例与佣金结算金额不能同时存在')
          return
        }
        if (!(data.obj && data.obj.sonServiceName && data.obj.price && data.obj.duration)) {
          message.error('请输入名称、价格、时长')
          return
        }
        console.log('flag', data.flag)
        console.log('数据=======', data.obj)
        if (data.flag > -1) {
          data.dataSource[data.flag] = {
            sonServiceName: data.obj.sonServiceName,
            price: data.obj.price,
            duration: data.obj.duration,
            serviceNum: data.obj.serviceNum,
            mallPrice: data.obj.mallPrice,
            commissionSettlementAmount: data.obj.commissionSettlementAmount || null,
            commissionSettlementRatio: data.obj.commissionSettlementRatio || null,
            operation: '',
            id: data.obj.id
          }
          console.log('实际', data.dataSource[data.flag])
          data.flag = -1
        } else {
          data.dataSource.pop()
          data.dataSource.push({
            sonServiceName: data.obj.sonServiceName,
            price: data.obj.price,
            serviceNum: data.obj.serviceNum,
            mallPrice: data.obj.mallPrice,
            duration: data.obj.duration,
            commissionSettlementAmount: data.obj.commissionSettlementAmount || null,
            commissionSettlementRatio: data.obj.commissionSettlementRatio || null,
            operation: ''
          })
        }
        console.log('实际', data.dataSource)

        data.obj = {}
      }
    }
    // 工作流程
    const formRef = ref()
    const dynamicValidateForm = reactive({
      serveName: '',
      users: [],
      id: Date.now()
    })
    const handleEditFlow = (item, index) => {
      console.log(data.dataFlow[index], '00000000')
      dynamicValidateForm.isEdit = true
      dynamicValidateForm.serveName = item.serveName
      dynamicValidateForm.id = item.id
      dynamicValidateForm.users = JSON.parse(item.users)

      data.flowPop = true
    }
    const removeService = index => {
      // let index = data.serviceDetail.indexOf(item);
      // if (index !== -1) {
      data.serviceDetails.splice(index, 1)
    }
    const removeUser = item => {
      let index = dynamicValidateForm.users.indexOf(item)
      // if (index !== -1) {
      dynamicValidateForm.users.splice(index, 1)
      // }
    }
    const addServiceDetail = () => {
      console.log(data.serviceDetails, 'res.serviceDetailsres.serviceDetails-----')

      data.serviceDetails.push({
        serviceDetailTitle: '',
        serviceDetail: ''
      })
    }
    const handleClick = i => {
      data.active = i
    }
    const addUser = () => {
      dynamicValidateForm.users.push({
        first: '',
        last: '',
        id: Date.now()
      })
      console.log(dynamicValidateForm.users, '-------')
    }
    const onFinish = values => {
      if (dynamicValidateForm.users.length == 0) {
        message.error('请至少输入一条规范详情')
        return
      }
      if (dynamicValidateForm.isEdit) {
        data.dataFlow = data.dataFlow.map(d => {
          if (d.id == dynamicValidateForm.id) {
            return {
              id: dynamicValidateForm.id,
              serveName: dynamicValidateForm.serveName,
              users: JSON.stringify(dynamicValidateForm.users)
            }
          }
          return d
        })
      } else {
        data.dataFlow.push({
          id: dynamicValidateForm.id,
          serveName: dynamicValidateForm.serveName,
          users: JSON.stringify(dynamicValidateForm.users)
        })
      }
      console.log('Received values of form:', {
        ...dynamicValidateForm
      })
      console.log('dynamicValidateForm.users:', dynamicValidateForm)
      closeFlowPop()
    }

    const loadData = async selectedOptions => {
      console.log('点击了选择----------------', selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true // load options lazily
      let obj = {
        parentId: targetOption.id
      }
      let res = await api.selectAllType(obj)
      if (res.success) {
        // res.object.records.map((el) => (el.name = el.serveName));
        targetOption.children = res.object
        data.typeList = [...data.typeList]
      }
    }
    return {
      formRef,
      dynamicValidateForm,
      onFinish,
      handleMyChange,
      removeUser,
      addUser,
      ...toRefs(data),
      ...methods,
      childrenColums,
      myColums,
      pagination,
      serviceAct,
      serviceColums,
      addService,
      delService,
      typeChange,
      editService,
      getChildrenList,
      handleTableChange,
      up,
      down,
      changeStack,
      checkConsumable,
      modalRef,
      imageUrl,
      labelCol: {
        style: {
          width: '150px',
          fontWeight: 'bold'
        }
      },
      wrapperCol: {
        span: 12
      },
      previewVisible,
      previewImage,
      rules,
      modalRef1,
      rules1,
      tinymceInput1,
      tinymceInput,
      handleCancel,
      handlePreview,
      handleChange,
      handleChange1,
      beforeUpload,
      save,
      cancel,
      headerTitle,
      uploadImage,
      uploadImage2,
      uploadImage3,
      uploadImage4,
      uploadImage5,
      delMyImg,
      editor,
      editor1,
      closeFlowPop,
      handleEditFlow,
      addServiceDetail,
      removeService,
      handleClick,
      loadData,
      handleAddContentImg,
      handleClose,
      handleAddContentImgOpen,
      customRow,
      serviceUploadImage,
      peopleUploadImage,
      processUploadImage,
      instructionsUploadImage,
      feeUploadImage,
      imgUrlUploadImage,
      popularImage,
      state
      // validImage
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    EditTwoTone,
    DeleteTwoTone,
    ArrowUpOutlined,
    ArrowDownOutlined,
    PlusOutlined,
    LoadingOutlined,
    Tinymce,
    Tinymce1,
    UploadImage,
    MinusCircleOutlined
  }
}
</script>

<style scoped lang="less">
.form-button {
  display: block;
  white-space: nowrap;
}
// .ant-tabs-nav-list{
// 	.ant-tabs-tab .ant-tabs-tab-active{
// 		::v-deep.ant-tabs-tab-btn{
// 			color: #fff !important;
// 			text-shadow: 0 0 0.25px currentcolor;
// 		}
// 	}
.ant-tabs-tab .ant-tabs-tab-active .ant-tabs-tab-btn {
  color: #fff;
  text-shadow: 0 0 0.25px currentcolor;
}

.flex {
  display: flex;
  align-items: center;
}

.main {
  display: flex;
  margin-top: 30px;
}

.header {
  margin-top: 20px;

  .tab {
    padding: 6px 24px;
    margin-right: 16px;
    background: #eee;
    border-radius: 4px;

    &.active {
      color: #fff;
      background: #006d77;
    }
  }
}

.ant-upload-text {
  padding: 40px;
  display: flex;
}

.service {
  display: flex;
  padding: 4px 40px;
  justify-content: space-between;

  // 服务激活样式
  .name-act {
    color: #2a9d8f;
    font-weight: bolder;
  }

  .edit {
    padding: 0px 5px;
  }
}

.process {
  display: flex;

  .process-list {
    margin-right: 20px;
    display: flex;
    flex-direction: column;

    .num {
      width: 50px;
      height: 50px;
      border: solid 1px #999;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
    }

    .img {
      width: 50px;
      height: 50px;
      background-color: tomato;
      margin: 10px 0px;
    }

    .title {
    }
  }
}

.table {
  width: 100%;
  border-left: 1px solid #eee;
  border-top: 1px solid #eee;

  tr {
    td {
      input {
        border: 1px solid #aaa !important;
        width: 97% !important;
      }
    }

    th,
    td {
      text-align: center;
      border-right: 1px solid #eee;
      border-bottom: 1px solid #eee;
    }
  }
}

.myhtml {
  width: 160%;
  height: 140%;
  padding: 8rpx 6rpx;
  border: 2rpx solid #d9d9d9;
  border-radius: 2px;
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
}

.flowWrap {
  .f_item {
    padding: 20px 0 !important;
  }

  .left {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 22px;
    margin-right: 30px;

    .spot {
      color: red;
    }
  }
}

.ant-form-item {
  margin-bottom: 0px;
}
</style>
